package com.feimt.interceptor;

import com.alibaba.fastjson.JSON;
import com.feimt.utils.BaseContent;
import com.feimt.result.R;
import com.feimt.utils.PathMatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 宋孟林
 * @description
 */
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("url: {}", request.getRequestURI());
        //如果匹配上就返回true，否则false
        boolean check = PathMatcher.check(request.getRequestURI());
        if (check) {
            return true;
        }
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContent.setThreadLocal(userId);
            return true;
        }
        Long auth = (Long) request.getSession().getAttribute("auth");
        if (auth != null) {
            BaseContent.setThreadLocal(auth);
            return true;
        }
        //不是静态资源也没有登陆就拦截
        //设置状态码
        response.setStatus(401);
        //设置响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
